<?php

namespace app\admin\service\science;

use think\Db;
use think\Exception;
use app\common\model\SpjFeedback;

class FeedbackService
{
    /**
     * 获取反馈列表
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function list()
    {
        $page = request()->param('page', 1);
        $limit = request()->param('limit', 10);
        $status = request()->param('status', '');
        $scene = request()->param('scene', '');
        $id = request()->param('id', '');
        $user = request()->param('user', '');
        $query = SpjFeedback::order('create_time', 'desc');

        if ($status !== '') {
            $query->where('status', $status);
        }
        if ($scene !== '') {
            $query->where('scene', $scene);
        }

        if ($id !== '') {
            $query->where('id', $id);
        }
        if ($user !== '') {
              $query->whereExists(function($query)use($user){
                  $query->table('spj_user')
                  ->where('id','=',new \think\db\Raw('spj_feedback.user_id'))
                  ->where('name','like','%'.$user.'%');
              });
          }
        $query->with(['user'=>function($query){
            $query->field('id,name,avatar');
        }]);
        $list = $query->paginate(request()->get('page_size/d', 10));
        return $list;
    }

    /**
     * 获取反馈详情
     * @param int $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $id)
    {
        $feedback = SpjFeedback::findOrFail($id);
        $feedback['images'] = json_decode($feedback['images'],true);
        $feedback['scene'] = strval($feedback['scene']);
        $feedback['status'] = strval($feedback['status']);
        return $feedback;
    }

    /**
     * 处理反馈
     * @param int $id
     * @param $request
     * @return bool
     * @throws Exception
     */
    public function process(int $id, $request)
    {
        $feedback = SpjFeedback::find($id);
        if (!$feedback) {
            throw new Exception('反馈记录不存在');
        }

        $status = $request->param('status');
        $processRemark = $request->param('process_remark', '');

        $feedback->status = $status;
        $feedback->process_remark = $processRemark;
        $feedback->update_time = time();
        // 可以根据实际需求添加处理人字段
        // $feedback->process_by = ...;
        return $feedback->save() !== false;
    }

    /**
     * 删除反馈
     * @return array
     * @throws Exception
     */
    public function delete()
    {
        $ids = request()->param('id/a');
        if (!$ids) {
            throw new Exception('请选择要删除的记录');
        }

        $result = SpjFeedback::destroy($ids);
        if (!$result) {
            throw new Exception('删除失败');
        }

        return ['affected_rows' => $result];
    }
}